package com.yg.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yg.config.FilePathConfig;
import com.yg.config.result.R;
import com.yg.config.result.ResultCode;
import com.yg.entity.readAndWriteTemplates.PublicationsRead;
import com.yg.entity.singleTemplates.Publications;
import com.yg.mapper.PublicationsMapper;
import com.yg.service.PublicationsService;
import com.yg.utils.DateValidationUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 对应sheet14，此表是本科生发表文章表 服务实现类
 * </p>
 *
 * @author YingGu
 * @since 2020-11-04
 */
@Service
public class PublicationsServiceImpl extends ServiceImpl<PublicationsMapper, Publications> implements PublicationsService {

    @Autowired
    PublicationsMapper publicationsMapper;
    @Autowired
    FilePathConfig filePathConfig;

    /**
     * excel写入
     *
     * @param fileInputStream
     * @return
     */
    @Override
    public R readExcel(FileInputStream fileInputStream) {
        //创建要录入的bean的list
        List<Publications> publicationsList = new ArrayList<>();
        //创建R
        R r = R.getR();
        r.setCode(ResultCode.SUCCESS);
        //存储错误信息
        List<String> errorList = new ArrayList<>();
        //读取excel
        EasyExcel.read(fileInputStream, PublicationsRead.class, new AnalysisEventListener<PublicationsRead>() {
            //每行执行
            @Override
            public void invoke(PublicationsRead publicationsRead, AnalysisContext context) {
                Publications publication = new Publications();
                publicationsRead.setTime(DateValidationUtil.dateValidation(publicationsRead.getTime(), "yyyy.MM"));
                System.out.println("excel表中：" + publicationsRead);
                BeanUtils.copyProperties(publicationsRead, publication);
                System.out.println("转换：" + publication);
                publicationsList.add(publication);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                if (r.getCode() == ResultCode.SUCCESS) {
                    saveData();
                } else {
                    r.data("errorMsg", errorList);
                }
            }

            /**
             * 数据类型转换异常处理
             * @param exception
             * @param context
             * @throws Exception
             */
            @Override
            public void onException(Exception exception, AnalysisContext context) throws Exception {
                if (exception instanceof ExcelDataConvertException) {
                    ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;

                    //向errorList中添加信息
                    r.code(ResultCode.ERROR);
                    System.out.println("行：" + excelDataConvertException.getRowIndex() + "列" + excelDataConvertException.getColumnIndex());
                    errorList.add("行：" + excelDataConvertException.getRowIndex() + "列" + excelDataConvertException.getColumnIndex());
//                    LOGGER.error("第{}行，第{}列解析异常", excelDataConvertException.getRowIndex(),
//                            excelDataConvertException.getColumnIndex());
                }
            }

            //存数据库操作
            private void saveData() {
                for (Publications publication : publicationsList) {
                    publicationsMapper.insert(publication);
                    System.out.println("插入成功");
                }

                //r中写入成功信息
                r.code(ResultCode.SUCCESS).message("插入成功");
            }
        }).headRowNumber(6).sheet().doRead();
        return r;
    }

    /**
     * excel写出
     *
     * @return
     */
    @Override
    public R writeExcel(HttpServletResponse response, PublicationsRead publicationsRead) {
        List<Publications> publications = new ArrayList<>();

        if (publicationsRead == null) {
            publications = publicationsMapper.selectAllPublications1();
        } else {
            if (publicationsRead.getStartAndEnd() != null) {
                String[] strings = publicationsRead.getStartAndEnd().split("-");
                publicationsRead.setStart(strings[0]);
                publicationsRead.setEnd(strings[1]);
            }
            Publications publication = new Publications();
            BeanUtils.copyProperties(publicationsRead, publication);
            publications = publicationsMapper.publicationsConditionalQuery1(publication);

        }
        List<PublicationsRead> publicationsReads = new ArrayList<>();
        for (int i = 0; i < publications.size(); i++) {
            PublicationsRead publicationRead = new PublicationsRead();
            BeanUtils.copyProperties(publications.get(i), publicationRead, new String[]{"physicsProperties"});
            publicationRead.setPhysicsLettersAndPageNumbers(publications.get(i).getPhysicsLetters() + "，" + publications.get(i).getPageNumbers());
            if ("SCI".equals(publications.get(i).getPhysicsProperties())) {
                publicationRead.setPhysicsProperties("√");
            } else if ("中文核心".equals(publications.get(i).getPhysicsProperties())) {
                publicationRead.setPhysicsProperties1("√");
            } else {
                publicationRead.setPhysicsProperties2("√");
            }
            publicationRead.setNum(i+1);
            publicationsReads.add(publicationRead);
        }
        //导出(匿名内部类SheetWriteHandler)
        try {
            String fileName = URLEncoder.encode("sheet14指导论文", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
            EasyExcel.write(response.getOutputStream()).withTemplate(filePathConfig.writeExcelFilePath + "sheet14Template.xlsx").registerWriteHandler(new SheetWriteHandler() {
                @Override
                public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

                }

                @Override
                public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

                }
            }).sheet().doFill(publicationsReads);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.OK();
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public R selectAllPublications(String current, String limit) {
        Page<Publications> publicationsPage = new Page<>(Integer.valueOf(current), Integer.valueOf(limit));
        IPage<Publications> publicationsIPage = publicationsMapper.selectAllPublications(publicationsPage);
        List<Publications> records = publicationsIPage.getRecords();
        return records.size() != 0 ? R.OK().data("list", records).data("pages", publicationsIPage.getPages()).data("total", publicationsIPage.getTotal()) : R.OK().message("您所查询的信息不存在").data("list", records);
    }

    /**
     * 条件查询
     *
     * @param publicationsRead
     * @return
     */
    @Override
    public R conditionalQuery(PublicationsRead publicationsRead, String current, String limit) {
        Page<PublicationsRead> publicationsReadPage = new Page<>(Integer.valueOf(current), Integer.valueOf(limit));
        if (publicationsRead.getStartAndEnd() != null) {
            String[] strings = publicationsRead.getStartAndEnd().split("-");
            publicationsRead.setStart(strings[0]);
            publicationsRead.setEnd(strings[1]);
        }
        IPage<PublicationsRead> publicationsReadIPage = publicationsMapper.publicationsConditionalQuery(publicationsReadPage, publicationsRead);
        List<PublicationsRead> records = publicationsReadIPage.getRecords();
        return records.size() != 0 ? R.OK().data("list", records).data("pages", publicationsReadIPage.getPages()).data("total", publicationsReadIPage.getTotal()) : R.OK().message("您所查询的信息不存在").data("list", records);
    }

    /**
     * 更新
     *
     * @param publications
     * @return
     */
    @Override
    public R updatePublications(Publications publications) {
        publications.setTime(DateValidationUtil.dateValidation(publications.getTime(), "yyyy.MM"));
        int update = publicationsMapper.updateById(publications);
        return update == 1 ? R.OK().message(publications.getId() + publications.getStudentName() + "修改成功") : R.ERROR().code(ResultCode.UPDATEERROR).message(publications.getId() + publications.getStudentName() + "修改失败");
    }

    /**
     * 删除
     *
     * @param publications
     * @return
     */
    @Override
    public R deletePublicationById(Publications publications) {
        int id1 = publicationsMapper.deleteById(publications.getId());
        return id1 == 1 ? R.OK().message("删除成功") : R.ERROR().code(ResultCode.DELETEERROR).message("删除失败");
    }

    /**
     * 新增
     *
     * @param publications
     * @return
     */
    @Override
    public R insertPublications(Publications publications) {
        publications.setTime(DateValidationUtil.dateValidation(publications.getTime(), "yyyy.MM"));
        int insert = publicationsMapper.insert(publications);
        return insert == 1 ? R.OK().message(publications.getId() + publications.getStudentName() + "添加成功") : R.OK().message(publications.getId() + publications.getStudentName() + "添加失败");
    }
}
